package com.flowershop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flowershop.entity.CreativeProduct;
import com.flowershop.service.CreativeProductService;

@RestController
@RequestMapping("/api/creative-products")
@CrossOrigin
public class CreativeProductController {

    @Autowired
    private CreativeProductService creativeProductService;

    @GetMapping("/page")
    public Page<CreativeProduct> page(@RequestParam(defaultValue = "1") Integer current,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    @RequestParam(required = false) String name,
                                    @RequestParam(required = false) String category) {
        Page<CreativeProduct> page = new Page<>(current, size);
        LambdaQueryWrapper<CreativeProduct> queryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(CreativeProduct::getName, name);
        }
        if (category != null && !category.isEmpty()) {
            queryWrapper.eq(CreativeProduct::getCategory, category);
        }
        return creativeProductService.page(page, queryWrapper);
    }

    @GetMapping("/{id}")
    public CreativeProduct getById(@PathVariable Long id) {
        return creativeProductService.getById(id);
    }

    @PostMapping
    public CreativeProduct save(@RequestBody CreativeProduct product) {
        creativeProductService.save(product);
        return product;
    }

    @PutMapping
    public CreativeProduct update(@RequestBody CreativeProduct product) {
        creativeProductService.updateById(product);
        return product;
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return creativeProductService.removeById(id);
    }

    @PutMapping("/{id}/stock")
    public boolean updateStock(@PathVariable Long id, @RequestParam Integer quantity) {
        CreativeProduct product = creativeProductService.getById(id);
        if (product != null) {
            product.setStock(quantity);
            return creativeProductService.updateById(product);
        }
        return false;
    }
} 